package com.yifeng.nettyserver.controller;

import com.yifeng.netty.common.protobuf.UserInfo;
import com.yifeng.nettyserver.netty.NettyHolder;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * ClassName: IndexController
 * author: yifeng
 * date: 2020/6/5 15:25
 */
@RestController
public class IndexController {

    @Value("${netty.port}")
    private int port;

    @GetMapping("/port")
    public int port(){
        return port;
    }

    @GetMapping("/push/{id}")
    public String push(@PathVariable("id") Integer id){
        Channel channel = NettyHolder.get(id);
        UserInfo.UserMsg userMsg = UserInfo.UserMsg.newBuilder().setId(id).setAge(18).setName("zhangsan").setState(1)
                .build();
        channel.writeAndFlush(userMsg);
        return "推送成功";
    }

    @GetMapping("/pushAll")
    public String push(){
        Map<Integer, Channel> channels = NettyHolder.getAll();
        channels.forEach((id,channel) -> {
            UserInfo.UserMsg userMsg = UserInfo.UserMsg.newBuilder().setId(id).setAge(18).setName("zhangsan").setState(1)
                    .build();
            channel.writeAndFlush(userMsg);
        });
        UserInfo.UserMsg userMsg = UserInfo.UserMsg.newBuilder().setId(1).setAge(18).setName("zhangsan").setState(1)
                .build();
        return "推送成功";
    }

}
